package com.fly.luck.controller;

import java.io.File;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import com.fly.luck.service.TextService;
import com.fly.luck.service.TokenService;

@Controller
public class IndexController
{
    @Autowired
    HttpSession httpSession;
    
    @Autowired
    TextService textService;
    
    @Autowired
    TokenService tokenService;
    
    File root = new File("upload");
    
    @PostConstruct
    private void init()
    {
        root.mkdirs();
    }
    
    @GetMapping({"/", "/index"})
    public String index(Model model)
    {
        String token = (String)httpSession.getAttribute("token");
        if (tokenService.valide(token))
        {
            model.addAttribute("text", textService.getText());
            model.addAttribute("isLogin", true);
            model.addAttribute("sysTokenTime", tokenService.getTokenTime());
            if (root.exists())
            {
                List<File> files = FileUtils.listFiles(root, null, true).stream().filter(f -> f.isFile()).sorted(Comparator.comparing(File::getAbsolutePath)).collect(Collectors.toList());
                model.addAttribute("files", files);
                model.addAttribute("size", FileUtils.byteCountToDisplaySize(FileUtils.sizeOfDirectory(root)));
            }
        }
        return "/index";
    }
    
    @PostMapping("/login")
    public String login(String token)
    {
        if (tokenService.valide(token))
        {
            httpSession.setAttribute("token", token);
        }
        return "redirect:/index";
    }
    
    @GetMapping("/logout")
    public String logout()
    {
        httpSession.invalidate();
        return "redirect:/index";
    }
    
    @PostMapping("/text/submit")
    public String upload(String text)
    {
        textService.setText(text);
        return "redirect:/index";
    }
}
